package service

import (
	"errors"
	"mime/multipart"
	"os"
	"time"

	"gitee.com/cyanbleeze/go-image-management/global"
	"gitee.com/cyanbleeze/go-image-management/pkg/upload"
)

func (svc *Service) UploadFile(file *multipart.FileHeader) (string, error) {
	username, exist := svc.ctx.Get("username")
	if !exist {
		return "", errors.New("登录用户信息不存在")
	}
	name := file.Filename
	if !upload.CheckContainExt(name) {
		return "", errors.New("file suffix is not supported")
	}
	if !upload.CheckMaxSize(file.Size) {
		return "", errors.New("exceeded maximum file limit")
	}
	uploadSavePath := global.AppSetting.UploadSavePath
	if upload.CheckSavePath(uploadSavePath) {
		if err := upload.CreateSavePath(uploadSavePath, os.ModePerm); err != nil {
			return "", errors.New("failed to create save directory")
		}
	}
	if upload.CheckPermission(uploadSavePath) {
		return "", errors.New("insufficient file permissions")
	}
	encodeName := upload.GetFileName(username.(string)+" "+time.Now().Format("2006-01-02 15:04:05")) + upload.GetFileExt(name)
	filename := uploadSavePath + "/" + encodeName
	err := svc.ctx.SaveUploadedFile(file, filename)
	if err != nil {
		return "", err
	}
	thumbFilename := uploadSavePath + "/thumb/" + encodeName
	err = upload.CutImg(file, thumbFilename)
	if err != nil {
		return "", err
	}
	accessUrl := global.AppSetting.UploadServerUrl + "/" + encodeName
	return accessUrl, nil
}
